package com.Cfeng.XiaohuanChat.controller;

import com.Cfeng.XiaohuanChat.domain.CaptchaCodeVo;
import com.Cfeng.XiaohuanChat.domain.KaptchaConstant;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import lombok.RequiredArgsConstructor;
import org.springframework.security.web.authentication.session.SessionAuthenticationException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author Cfeng
 * @date 2022/8/21
 * 主要就是借助Kaptcha工具类生成动态的图片验证码，配合security进行验证登录，验证码放在redis的session中
 */

@RestController
@RequiredArgsConstructor
public class KaptchaController {
    //配置的kaptcha工具类
    private final DefaultKaptcha defaultKaptcha;

    /**
     * 前台请求验证码，返回资源，使用httpResponse返回
     */
    @GetMapping("/kaptcha")
    public void getKaptchaImage(HttpSession httpSession, HttpServletResponse response) throws IOException, SessionAuthenticationException {
        //设置相应的格式和类型
        response.setDateHeader("Expires",0);
        response.setHeader("Cache-control","no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        //创建验证码
        String capText = defaultKaptcha.createText();
        //将验证码放入session，会自动由Spring Session受理
        httpSession.setAttribute(KaptchaConstant.CAPTCHA_SESSION_KEY,new CaptchaCodeVo(capText,60)); //60s
        //返回响应
        BufferedImage bufferedImage = defaultKaptcha.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bufferedImage,"jpg",out);
        try {
            out.flush();
        } finally {
            out.close();
        }
    }
}
